package com.xxl.job.executor.service.jobhandler;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.mapper.AmapCityWeatherMapper;
import com.xxl.job.executor.mapper.BaseCityCodeMapper;
import com.xxl.job.executor.pojo.AmapCityWeather;
import com.xxl.job.executor.pojo.BaseCityCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * XxlJob开发示例（Bean模式）
 *
 * 开发步骤：
 *      1、任务开发：在Spring Bean实例中，开发Job方法；
 *      2、注解配置：为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 *      3、执行日志：需要通过 "XxlJobHelper.log" 打印执行日志；
 *      4、任务结果：默认任务结果为 "成功" 状态，不需要主动设置；如有诉求，比如设置任务结果为失败，可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果；
 *
 * @author WangBin
 */
@Component
public class GaoDeXxlJob {
    private static Logger logger = LoggerFactory.getLogger(GaoDeXxlJob.class);

    private static final String AMAP_API_KEY = "78c6dd6019bfa7745b7ad9d4d98321d4";
    private static final String AMAP_API_URL = "https://restapi.amap.com/v3/weather/weatherInfo";

    @Autowired
    AmapCityWeatherMapper cityWeatherMapper;
    @Autowired
    BaseCityCodeMapper baseCityCodeMapper;

    /**
     * 同步天气信息
     */
    @XxlJob("weatherJobHandler")
    public void demoJobHandler() throws Exception {
        XxlJobHelper.log("XXL-JOB, 正在执行同步天气信息...");

        // 删除实时天气信息
        Example example = new Example(AmapCityWeather.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("type", "lives");
        cityWeatherMapper.deleteByExample(example);
        XxlJobHelper.log("XXL-JOB, 已清除实时天气信息：");

        // 所有城市列表
        Example cityCodeExample = new Example(BaseCityCode.class);
        Example.Criteria cityCodeCriteria = cityCodeExample.createCriteria();
        List<Integer> notInList = new ArrayList<>();
        notInList.add(100000);
        notInList.add(130201);
        cityCodeCriteria.andNotIn("adcode", notInList);
        List<BaseCityCode> cityCodeList = baseCityCodeMapper.selectByExample(cityCodeExample);

        for (BaseCityCode cityCode : cityCodeList) {
            String url = AMAP_API_URL + "?key=" + AMAP_API_KEY + "&city=" + cityCode.getAdcode();
            String responseStr = HttpUtil.get(url);
            XxlJobHelper.log("XXL-JOB, 获取的天气信息：" + responseStr);
            // 转化 json
            JSONObject responseObj = JSONUtil.parseObj(responseStr);
            if(responseObj.getStr("status").equals("1")) {

                try {
                    JSONArray jsonArray = responseObj.getJSONArray("lives");
                    JSONObject weather = jsonArray.getJSONObject(0);

                    AmapCityWeather cityWeather = new AmapCityWeather();
                    cityWeather.setCityCode(cityCode.getAdcode());
                    cityWeather.setType("lives");
                    cityWeather.setWeather(weather.getStr("weather"));
                    cityWeather.setHumidity(weather.getStr("humidity"));
                    cityWeather.setProvince(weather.getStr("province"));
                    cityWeather.setWindpower(weather.getStr("windpower"));
                    cityWeather.setTemperature(weather.getStr("temperature"));
                    cityWeather.setCityName(cityCode.getName());
                    cityWeather.setReporttime(weather.getStr("reporttime"));
                    cityWeather.setUpatedAt(new Date());
                    cityWeatherMapper.insert(cityWeather);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        XxlJobHelper.log("XXL-JOB, 已同步实时天气信息：");
    }

    /**
     * 5、生命周期任务示例：任务初始化与销毁时，支持自定义相关逻辑；
     */
    @XxlJob(value = "demoJobHandlerLife", init = "init", destroy = "destroy")
    public void demoJobHandler2() throws Exception {
        XxlJobHelper.log("XXL-JOB, Hello World.");
    }
    public void init(){
        logger.info("init");
    }
    public void destroy(){
        logger.info("destory");
    }


}
